package org.xxpay.pay.channel.nzzpay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundAuthOrderAppFreezeModel;
import com.alipay.api.request.AlipayFundAuthOrderAppFreezeRequest;
import com.alipay.api.response.AlipayFundAuthOrderAppFreezeResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyBase64;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.ctrl.common.BaseController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @Description: 新支付宝转账
 * @author xxpay
 * @date 2020/1/7
 */
@Controller
public class NzzpayController extends BaseController {

	private static final MyLog _log = MyLog.getLog(NzzpayController.class);

	/**
	 * 转到前端收银台界面
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/api/"+ NzzpayConfig.CHANNEL_NAME+"/pay_{type}.htm")
	public String toPay(HttpServletRequest request, ModelMap model, @PathVariable("type") String type) {
		JSONObject po = getJsonParam(request);
		String amount = getString(po, "amount");
		String payOrderId = getString(po, "payOrderId");
		String mchOrderNo = getString(po, "mchOrderNo");
		Boolean autoJump = getBoolean(po, "autoJump");
		// 订单创建时间与当前时间差值(此处使用db计算，为了避免服务器和db时间有差异)
		Long expireTime = commonService.payOrderService.getOrderTimeLeft(payOrderId, NzzpayConfig.PAY_ORDER_TIME_OUT);
		if(expireTime == null || expireTime < 0) expireTime = 0l;
		String codeUrl = getString(po, "codeUrl");
		String codeImgUrl = getString(po, "codeImgUrl");
		model.put("amount", AmountUtil.convertCent2Dollar(amount));
		model.put("amountStr", "￥"+ AmountUtil.convertCent2Dollar(amount));
		model.put("mchOrderNo", mchOrderNo);
		model.put("payOrderId", payOrderId);
		model.put("expireTime", expireTime);
		model.put("codeUrl", codeUrl);
		model.put("codeImgUrl", codeImgUrl);
		model.put("autoJump", autoJump);
		return "payment/"+ NzzpayConfig.CHANNEL_NAME+"/pay_" + type;
	}

	/**
	 * 查询订单
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/api/"+ NzzpayConfig.CHANNEL_NAME+"/query")
	@ResponseBody
	public String toQuery(HttpServletRequest request) throws ServletException, IOException {
		JSONObject po = getJsonParam(request);
		String payOrderId = getString(po, "payOrderId");
		_log.info("[查询订单]参数payOrderId={}", payOrderId);

		PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
		JSONObject retObj = new JSONObject();
		String status = "-1";
		String url = "";
		if(payOrder != null) {
			status = payOrder.getStatus() + "";
			url = payOrder.getReturnUrl();
		}
		retObj.put("status", status);
		retObj.put("url", url);
		_log.info("[查询订单]结果payOrderId={},retObj={}", payOrderId, retObj);
		return retObj.toJSONString();
	}

	/**
	 * 支付宝红包界面
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/api/" + NzzpayConfig.CHANNEL_NAME + "/alipay_nzz_{param}.htm")
	public String alipayRed(ModelMap model, @PathVariable String param) {
		String paramJson = new String(MyBase64.decode(param));
		JSONObject po = JSONObject.parseObject(paramJson);
		String alipayUserId = getString(po, "alipayUserId");
		String alipayAccount = getString(po, "alipayAccount");
		String amount = getString(po, "amount");
		String payOrderId = getString(po, "payOrderId");
		model.put("amount", amount);
		model.put("tradeNo", payOrderId);
		model.put("alipayUserId", alipayUserId);
		model.put("alipayAccount", alipayAccount);
		model.put("alipayName", "");

		PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
		if(payOrder == null || payOrder.getStatus() != 1) {
			return "payment/" + NzzpayConfig.CHANNEL_NAME + "/pay_cs";
		}

		DBApplicationConfig dbConfig = commonService.sysConfigService.getDBApplicationConfig();
		//ws地址： ws://localhost:8088/ws/payOrder/P11100001/20180010101
		String payDomain = dbConfig.getConfig4PayUrl().replace("http://", "").replace("https://", "").replace("/api",""); //去掉http协议
		String wsProtocol = dbConfig.getConfig4PayUrl().startsWith("http://") ? "ws://" : "wss://"; //ws协议
		model.put("wsAddress", wsProtocol + payDomain + "/ws/payOrder/" + payOrderId + "/" + new Date().getTime());

		return "payment/" + NzzpayConfig.CHANNEL_NAME + "/alipay_nzz";
	}


	/**
	 * 界面
	 * @return
	 */
	@RequestMapping("/api/" + NzzpayConfig.CHANNEL_NAME + "/pay_cs.html")
	public String payCs() {
		return "payment/" + NzzpayConfig.CHANNEL_NAME + "/pay_cs";
	}

	/**
	 * 测试支付宝预授权
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/api/" + NzzpayConfig.CHANNEL_NAME + "/test.htm")
	public String test(ModelMap model1) {


		String gateway="https://openapi.alipay.com/gateway.do";
		String app_id="2088002256494345";
		// String app_id="2018041302549194";
		String notify_url="https://www.baidu.com/";

		String charset="UTF-8";
		String app_private_key="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDDJfPXHSS4KwW0yTGttxr5Bo3QpTU/6MwRe13dr6CwrKvmFp9pStgrZY/Fm2ZnCiuyUFDWJBOprbJ+wX0aZ+AFl2pZj/DmQbOFZ8U/kuJcK0BJv/STmHOMtH96mEe+ysrnF+ofjUhDlwCJlPuD5mZREeicIvweLkND5HGJKeOHX3LIlU6Tw+MKfwIA6udOqG7ssTbqm7HBaEeJ4sUqGBsev0j1rblvM54s2ni8UuKLFnt2TTo2hK45ibATDsoKRLyIU/dj3WPnao04Yb707SeKNX4sxSt6WI4YSGPIEYlED+bw6z61ryy4mrwEoxEo+v4q5T3NoH5rOhfY5hd9aTvTAgMBAAECggEAb+Rt+LSMHlEEt5D4vBsWCx036R8g9i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5XgiNT8wEU8CL1bfAc6pe4BiF79aEymToC1TL5Ist6WmPv7hzHpZli1mm6zis3lEVdbRtxHZd/HY6fcTL7RZirv3av3TU4DDVWlz35cd3DanGdrYyVFoWrSAvUHe+2vk=";
		String alpay_public_key="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnc/gFbC0iBnkCV4srbuEthOWyVIsdfaKZPY7vbHJASeOwTzhRjrb+U1ryVIgbGi/L4f6PBxzEpg+MwtIvY2tvW+urt8kPkVD/z1/+oPJoiDA303TlKMIA685Iu/aY+DGWDkfOQ5hHZQJ6bsCKj0+IVdWbEQluPLBx+T/P7hI2DHovDbSXiwl4S2E5MgOBVbT+7j13P+fNHeDAm3CrjBdcc9dvPA3F434vVUzGmsUQc1TSzM6F+K0uO6E8JFNqTQeBGD1szdG776ArUO7AF/Bz1xVUByXeEcaHhMNU2K0wE9qQRgpNlkk6xmEL3XyGONon2Zm4FeNUoEt6xfd0TX7tQIDAQAB";
		String  outorderno=""+System.currentTimeMillis();

		AlipayClient alipayClient = new DefaultAlipayClient(gateway,app_id,app_private_key,"json",charset,alpay_public_key,"RSA2");
		AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
		AlipayFundAuthOrderAppFreezeModel model = new AlipayFundAuthOrderAppFreezeModel();
		model.setOrderTitle("支付宝预授权");
		model.setOutOrderNo(outorderno);//替换为实际订单号
		model.setOutRequestNo(outorderno);//替换为实际请求单号，保证每次请求都是唯一的
		// model.setPayeeUserId("payee_user_id");//payee_user_id,Payee_logon_id不能同时为空
		model.setPayeeLogonId("2088422833986081");
		model.setProductCode("PRE_AUTH_ONLINE");//PRE_AUTH_ONLINE为固定值，不要替换
		model.setAmount("1");

		//需要支持信用授权，该字段必传
		model.setExtraParam("{\"category\":\"CREDIT_HOTEL_ONLINE\",\"outStoreCode\":\"charge002\",\"outStoreAlias\":\"beijing\"}"); //outStoreAlias将在用户端信用守护、支付信息、账单详情页展示
		//选填字段，指定支付渠道
		//model.setEnablePayChannels("[{\"payChannelType\":\"PCREDIT_PAY\"},{\"payChannelType\":\"MONEY_FUND\"},{\"payChannelType\":\"CREDITZHIMA\"}]");
		request.setBizModel(model);
		request.setNotifyUrl(notify_url);//异步通知地址，必填，该接口只通过该参数进行异步通知
		AlipayFundAuthOrderAppFreezeResponse response = null;//注意这里是sdkExecute，可以获取签名参数
		String body = "";
		try {
			response = alipayClient.sdkExecute(request);
		} catch (AlipayApiException e) {
			_log.error(e, "");
		}
		if(response.isSuccess()){

			body = response.getBody();

		} else {

		}

		_log.info("支付宝预授权body={}", body);
		model1.put("orderStr", body);

		return "payment/" + NzzpayConfig.CHANNEL_NAME + "/test";
	}

}
